<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>增删改查</title>
</head>

<body>


  <h2>键值对以<mark>;</mark>做分隔</h2>
  <button onclick="seeAllCookie()">查看所有Cookie</button>
  <button onclick="addCookie('name=tiger')">添加Cookie</button>
  <button onclick="sac('name')">查看指定 Cookie</button>
  <button onclick="modifyCookie('name=panda')">修改Cookie</button>
  <button onclick="clearCookie('name')">删除Cookie</button>

  <script>
    //查看所有Cookie
    const seeAllCookie = () => {
      //获取所有Cookie
      let allCookie = document.cookie;
      alert("所有Cookie是：" + allCookie);
    };

    //添加指定Cookie - 提供Cookie键值对：'name=tiger'
    const addCookie = (cookie) => {
      //拿到需要更改的值
      let str = cookie + ";";
      document.cookie = str;
      alert("添加Cookie：" + str);
    };

    //查看指定Cookie - 提供Cookie名
    const sac = (Name) => {
      let cookieValue = seeAppointCookie(Name);
      alert("您查询的Cookie名是：" + Name + "\n该Cookie的值是：" + cookieValue);
    };

    //修改指定Cookie - 提供Cookie名
    const modifyCookie = (cookie) => {
      let str = cookie + ";path=/;";
      document.cookie = str;
      alert("Cookie name已修改为：" + str);
    };

    //删除指定Cookie - 提供Cookie名
    const clearCookie = (name) => {
      let expires = new Date();
      //当前时间减去一秒,相当于立即过期(可以增减)
      expires.setTime(expires.getTime() - 1000);

      //expires是对应过期时间的设置,不设这个值,cookie默认在关闭浏览器时失效
      let str = name + "='clear';path=/;expires=" + expires.toGMTString() + "";
      document.cookie = str;
      alert("已删除Cookie：" + name);
    };

    //查询指定Cookie的值
    const seeAppointCookie = (cookieName) => {
      //获取所有Cookie
      let strCookie = document.cookie;
      // 获取数组中的所有cookie对
      //注意，这里split("; ")，分号后需留空
      let arrCookie = strCookie.split("; ");

      for (let i = 0; i < arrCookie.length; i++) {
        let arr = arrCookie[i].split("=");
        if (cookieName === arr[0]) {
          return arr[1];
        }
      }

      return "没有查到该Cookie";
    };
  </script>
</body>

</html>